#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>

struct thrd{
    int var;
    char str[256];
};
void sys_error(const char *msg)
{
    perror(msg);
    exit(1);
}
void *tfn()
{
    printf("thread:pid=%d, tid:%lu\n", getpid(), pthread_self());
    struct thrd *tval;
    tval = malloc(sizeof(tval));
    strcpy(tval->str, "hello");
    return (void *)tval;
}
int main(int argc, char const *argv[])
{
    pthread_t tid1,tid2;
    pthread_attr_t attr;
    struct thrd *retval;
    printf("main:pid:%d, tid:%lu\n", getpid(), pthread_self());
    int ret = pthread_create(&tid1,NULL,tfn,NULL);
    ret = pthread_join(tid1, (void **)&retval);
    sleep(1);
    printf("child exit with var=%d, str=%s", retval->var, retval->str);
    ret = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
    ret = pthread_create(&tid2, &attr, tfn, NULL);
    pthread_attr_destroy(&attr);
    ret = pthread_join(tid2, (void **)&retval); // 报错就说明线程已经自动回收，设置分离成功。
    printf("child2 exit with var=%d, str=%s", retval->var, retval->str);
    //主线程退出，其他线程不退出，应用pthread_exit
    pthread_exit((void *)0);
}